<script lang="ts" setup>
import { ref, reactive, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { mStyles } from "@/utils/useStyles";
import { useStore } from "@/stores/user";
import { someFieldStore } from "@/stores/somefield";
import { request } from "@/service/request";
import API from "@/service/api/order";
import kf from "@/service/api/faq";
import cCountDown from "@/components/business/cCountDown.vue";
import { useCustomCountdown } from '@/hook/useCountDown';
import { requestToast } from "@/utils/requestToast";
import rules from "@/utils/rule";
import { useDynamicKeepAlive } from '@/utils/keepAliveUtils'
import { getUrlParamValue } from "@/utils/getUrlParams";

// UID
const mStore = useStore();
const mRoute = useRoute();
const mRouter = useRouter();
const mInfo = mRoute.query;

interface FormField {
    id: number;
    part_name: string;
    part_key: string;
    part_type: 1 | 2 | 3; // 1:单行文本, 2:多行文本, 3:图片上传
    is_require: 0 | 1;   // 0:非必填, 1:必填
    tips_content: string;
    max_num: number;
}


// 表单配置 - 根据您提供的数组
const mFormConfig = ref<FormField[]>([])

// 表单数据
const mSubmit = ref(true)
const mFormData = reactive<Record<string, any>>({
    game_id: 0,
    game_name: '',
    uid: Number(mStore.token.uid),
    role_id: '',
    role_name: "",
    server_name: '',
    order_template_code: '',
    detail: '',
    phone: '',
    sms_code: '',
    // 动态表单字段
    order_parts: [],
    restart: {
        img: [],
        remark_content: ''
    }
});


// 获取工单模板
const clkGetTemplate = async () => {
    mFormData.game_id = Number(mFormData.game_id);

    const { data } = await request.post<any>(API.orderTemplate, {
        id: Number(mInfo.work_order_template_id),
    });
    // 如果需要从接口获取表单配置，可以在这里替换formConfig的值
    mFormData.order_template_code = data.unique_code;
    mFormConfig.value = data.template_parts;

    // 初始化所有图片字段为空数组
    mFormConfig.value.forEach(field => {
        if (field.part_type === 3) {
            mFormData[field.part_key] = [];
        }
    });
};

//赋值对应的用户信息
Object.keys(mInfo).forEach(key => {
    if (key in mFormData) {
        mFormData[key] = mInfo[key];
    }
});

clkGetTemplate();


// 动态表单验证
const mDynamicFormRef = ref<any>(null);
const clkDynamicsValidateForm = () => {
    let isValid = true;
    mFormConfig.value.forEach(field => {
        if (!mDynamicFormRef.value.validate(field)) {
            isValid = false;
        }
    });

    if (!mFormData.phone) {
        //showToast('手机号不能为空');
        isValid = false;
    } else if (!rules.phone[1].pattern?.test(mFormData.phone)) {
        //showToast('请输入有效的手机号');
        isValid = false;
    }

    if (!mFormData.sms_code) {
        //showToast('手机验证码不能为空');
        isValid = false;
    }

    return isValid;
};

//点亮提交信息按钮
watch(
    () => clkDynamicsValidateForm(),
    (newConfig) => {
        if (clkDynamicsValidateForm()) {
            mSubmit.value = false;
        } else {
            mSubmit.value = true;
        }
    },
    { deep: true }
);

//提交成功后
const mKfShow = ref(true);
const mPhoneMactionSheetRef = ref();
// 倒计时功能
const { startCountdown, remaining } = useCustomCountdown({
    onCompleted: () => {
        mKfShow.value = false;
    }
});

// 提交表单
const mSomefield = someFieldStore();

//如果给了gameid就用给的
if(getUrlParamValue('game_id', mSomefield.clientfields) != null && getUrlParamValue('game_id', mSomefield.clientfields) != '') {
   mFormData.game_id = getUrlParamValue('game_id', mSomefield.clientfields);
   mFormData.game_id = Number(mFormData.game_id);
}

const clkSubmitForm = async () => {
    if (clkDynamicsValidateForm()) {
        // 表单提交逻辑
        const dynamicFields = mDynamicFormRef.value.getFormData();

        // 1. 构造外层数据（只保留基础字段，不包含动态字段和 order_parts）
        const baseFormData: Record<string, any> = {};
        Object.keys(mFormData).forEach(key => {
            baseFormData[`sys_${key}`] = mFormData[key];
        });

        // 2. 构造 order_parts，只包含动态表单字段
        const orderParts = mFormConfig.value.map(field => ({
            part_key: field.part_key,
            part_name: field.part_name,
            part_value: field.part_type !== 3
                ? (dynamicFields[field.part_key] !== undefined
                    ? dynamicFields[field.part_key]
                    : '')
                : '',
            pic_value: field.part_type === 3
                ? ((dynamicFields[field.part_key] ?? []).map((item: { path: any }) => item.path) || [])
                : null
        }));

        // 3. 最终提交对象
        const submitData = {
            ...baseFormData,
            sys_order_parts: orderParts
        };

        const { status, data } = await requestToast(submitData, API.orderWsubmit, "提交成功")
        if (status) {
            mKfShow.value = true;
            mPhoneMactionSheetRef.value.openDialog();
            mSomefield.order_num = data.order_num; // 保存工单号
            startCountdown(10);
        }
    } else {
        console.log('表单数据:', mFormData);
    }
};

const { removeCachedView } = useDynamicKeepAlive()

//确定按钮点击
const clkBeforeClose = () => {
    //提交成功移除缓存
    removeCachedView(mRoute)
    //通知列表页刷新
    removeCachedView('', 'order')

    mPhoneMactionSheetRef.value.closeDialog()
    // 跳转到工单列表页面
    mRouter.push({
        path: '/order',
        query: {
            active: 'processing'
        }
    })
}

</script>

<template>
    <cNavbar iTitle="找回账号" :iFontColor="mStyles?.color2" :iBgColor="mStyles?.color10" leftArrow iFixed></cNavbar>
    <div class="gr-height">
        <div class="gr-solve">
            <cVanForm>
                <div class="gr-input">
                    <label class="form-label text-[30px]">
                        <span class="color-[#FF3A37] m-r-[3px]">*</span>
                            情况描述
                    </label>
                    <cVanfield type="textarea" placeholder="请准确描述您遇到的问题以及上传相关截图，以便为您提供更好帮助..." autosize v-model="mFormData.detail"
                        maxlength="1000" show-word-limit class="m-t-[25px] m-b-[25px] text-[16px] font-normal"></cVanfield>
                </div>
                <cDynamicForm :formConfig="mFormConfig" v-model:formData.sync="mFormData" ref="mDynamicFormRef" />
                <div class="gr-order-phone m-t-[20px]" v-if="!mInfo.orderNum">
                    <label class="form-label text-[30px] font-medium">
                        <span class="color-[#FF3A37] m-r-[3px]">*</span>
                        联系手机号
                    </label>
                    <cVanfield v-model="mFormData.phone" placeholder="请输入手机号，处理结果将以短信形式通知到您" name="phone" clearable
                        class="m-b-[20px] m-t-[20px]">
                    </cVanfield>
                    <cCountDown v-model:code="mFormData.sms_code" :phone-number="mFormData.phone"></cCountDown>
                </div>
            </cVanForm>
        </div>
        <div class="gr-button">
            <cButton iLinearGradien class="w-[100%]" :iColor="mStyles?.color10" @click="clkSubmitForm"
                :disabled="mSubmit" round>
                提交信息
            </cButton>
        </div>
        <cVanActionSheet ref="mPhoneMactionSheetRef" :close-on-click-overlay="false" :iClose="false" :iButton="true"
            iText="查看工单" @is-Confirm="clkBeforeClose">
            <h1 class="text-[28px] m-b-[35px]">你的问题工单已提交成功，请耐心等待短信通知！</h1>
            <a :href="kf.getKfUrl()" v-show="mKfShow" class="gr-kf">
                <van-image src="/kf.png" width="6.4vmin" ></van-image>
                <span>联系在线客服<span class="text-[#FF3A37]">{{ `${remaining}s` }}</span></span>
            </a>
        </cVanActionSheet>
    </div>
</template>

<style lang="scss" scoped>
:deep(.van-field__clear){
    bottom: 0;
    right: 0;
    position: absolute;
}
:deep(.van-cell__value) {
    font-size: 30px;
    color: #3D3D3D;
}

:deep(.van-cell) {
    padding: 0 0 0 10px;
    overflow: visible;
}

.gr-input {
    border-radius: 24px;
    margin-bottom: 20px;
    padding:30px 20px 30px 20px;
    position: relative;
    background:#ffff;
    :deep(.van-field__word-limit) {
        font-size: 24px;
        color: rgba(61, 61, 61, 0.6);
        position: absolute;
        top: -70px;
        right: 0;
        z-index: 99;
    }
}

.gr-height {
    padding: 23px 23px 170px 23px;
    background: #F6F6F6;
}

.gr-info {
    margin: 10px;
    border-radius: 20px;
}

.gr-solve {
    border-radius: 20px;
}

.form {
    padding: 15px;
    background-color: #fff;
}

.gr-order-phone {
    border-radius: 24px;
    padding: 20px;
    background: #FFFFFF;
    margin-bottom: 20px;

    :deep(.van-cell:after) {
        border: none;
    }

    :deep(.van-cell) {
        padding: 0 0 0 0px;
        overflow: visible;
    }

    .phone {
        padding-bottom: 0px;
    }
}

.gr-button {
    position: fixed;
    left: 0;
    right: 0;
    bottom: env(safe-area-inset-bottom);
    background: white;
    padding: 45px;
}

.gr-kf {
    color:#3D3D3D;
    display: inline-flex;
    align-items: center;
}
</style>